package com.zxx.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.zxx.ssm.dao.Employee;
import com.zxx.ssm.dao.EmployeeExample;
import com.zxx.ssm.dao.Leaves;
import com.zxx.ssm.dao.LeavesExample;
import com.zxx.ssm.model.biz.LeavesBiz;
import com.zxx.ssm.model.convertor.LeavesConvertor;
import com.zxx.ssm.model.enums.ResultCode;
import com.zxx.ssm.model.form.LeavesForm;
import com.zxx.ssm.model.result.BizResponse;
import com.zxx.ssm.service.EmployeeService;
import com.zxx.ssm.service.LeavesService;
import com.zxx.ssm.util.DateUtils;
import com.zxx.ssm.util.PaginationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by zxx on 2016/12/17.
 */
@RestController
@RequestMapping("checkLeaves")
public class CheckLeavesController {
    @Autowired
    private LeavesService leavesService;

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public BizResponse getAll(@ModelAttribute LeavesForm leavesForm, @RequestParam(defaultValue = "1") int pageNumber, @RequestParam(defaultValue = "10") int pageSize,
                              @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "desc") String order, HttpServletRequest request) {
        PaginationUtil.preset(pageNumber, pageSize, sort, order);
        leavesForm.setStartTime(DateUtils.convertString(leavesForm.getStartTime()));
        leavesForm.setEndTime(DateUtils.convertString(leavesForm.getEndTime()));
        if (leavesForm.getType() != null)
            leavesForm.setType(leavesForm.getType());
        HttpSession session = request.getSession();
        Employee curEmployee = (Employee) session.getAttribute("user");
        leavesForm.setEmployeeId(curEmployee.getId());
        if (curEmployee.getLevel() == 2)
            leavesForm.setState(1);
        if (curEmployee.getLevel() == 3)
            leavesForm.setState(2);
        leavesForm.setCurUserDepartmentId(curEmployee.getDepartmentId());
        List<LeavesBiz> leavesBizList = leavesService.getAllFromCurUserDepartment(leavesForm);
        PageInfo pageInfo = new PageInfo(leavesBizList);
        BizResponse bizResponse = new BizResponse();
        bizResponse.put("leaves", pageInfo);
        return bizResponse;
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public BizResponse update(@ModelAttribute LeavesForm leavesForm) {
        Leaves leaves = LeavesConvertor.convertLeavesForm(leavesForm);
        if (leavesService.updateByPrimaryKeySelective(leaves) > 0)
            return new BizResponse();
        else
            return new BizResponse(ResultCode.LEAVES_TYPE_UPDATE_ERROR);
    }
}
